#pragma once

#include <string>
#include <string.h>
#include <unordered_map>
#include <unordered_set>
#include <functional>
#include <mutex>
#include <pthread.h>
#include "mongoose.h"

using ReqHandler = std::function<bool (std::string, std::string, void* arg)>;/* 定义http请求handler */

class HttpServer
{
public:
    HttpServer();
    ~HttpServer();
    void Init(const std::string &addr);                               /* 初始化 */
    bool Start();                                                     /* 启动httpserver */
    bool Close();                                                     /* 关闭 */
    bool AddHandler(const std::string &url, ReqHandler req_handler, void *arg = NULL);  /* 注册事件处理函数 */
    void RemoveHandler(const std::string &url);                       /* 移除时间处理函数 */
private:
    static void OnHttpWebsocketEvent(mg_connection *connection, int event_type, void *event_data);/*静态事件响应函数*/
    static void HandleHttpEvent(mg_connection *connection, http_message *http_req);               /* 处理http事件 */
    static void SendHttpRsp(mg_connection *connection, std::string result);                       /* 发送http返回信息 */

    static void *IOThread(void*arg);
    static void *WorkerThread(void *param);
    bool RouteCheck(http_message *http_msg, char *route_prefix);
    static void on_work_complete(struct mg_connection *nc, int ev, void *ev_data);
private:
    struct HttpServerCallBackBind/* 用户注册的回调函数及参数的绑定 */
    {
        ReqHandler func;
        void * arg;
    };
    struct HttpThreadArgs
    {
        pthread_t threadID;  /* IO线程ID */
        bool isRunning;      /* 运行标志 */
        std::string addr;    /* HttpServer端口 */
        mg_mgr manager;      /* 连接管理器 */
        std::unordered_map<std::string, HttpServerCallBackBind> handlerMap;  /* 回调函数映射表 */
        std::mutex mtx;
        sock_t sockfd[2];    /* IO线程和工作线程通讯的socket */
    };
    HttpThreadArgs  m_args;  /* 线程参数 */
    struct work_request      /* 用于IO线程向工作线程发送请求 */
    {
        mg_connection *connection;
        http_message http_req;
        ReqHandler func;
        void *userArg;
    };

    struct work_result    /* 用于工作线程向IO线程返回结果 */
    {
        char retBuf[32];
    };
};

